import { Feature } from "ol";
import { LineString, Point, Polygon } from "ol/geom";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { olStyle } from "../style/styleclass";
import MapUtilsModel from "@/components/map/utils/map-utils";
import { GeoJSON } from "ol/format";
import { TileWMS } from "ol/source";
import TileGrid from "ol/tilegrid/TileGrid";
import TileLayer from "ol/layer/Tile";
import { LayerConstant } from "./LayerConstant";
import Icon from "ol/style/Icon";
import Style from "ol/style/Style";
export class LayerManager {
  currentMap;
  industryMapLayers = [];
  interactionDrawLayer = null; //绘制点图层
  interactionMeasureLayers = []; //测量图层
  measureLayerId=0
  constructor(map) {
    this.currentMap = map;
    this.MapUtils = new MapUtilsModel();
  }
  /**
   * 创建图层
   * config 层配置文件
   */
  createLayer(config) {
    let pointLayer = {
      id: config.id,
      zindex: config.zindex,
      visible: config.visible,
      cluster: config.cluster,
      layer: null,
    };
    let Source = new VectorSource();
    let vectorLayer = new VectorLayer({
      source: Source,
      style: null,
      zIndex: config.zIndex,
    });
    pointLayer.layer = vectorLayer;
    this.industryMapLayers.push(pointLayer);
    this.addLayerToMap(pointLayer);
    this.creatfeatures(pointLayer, config);
  }
  /**
   * 创建点元素
   * @param {*} Layer
   * @param {*} config
   * @returns
   */
  creatfeatures(pointLayer, config) {
    let features = [];
    if (config.data.length) {
      config.data.forEach((element) => {
        const currentFeature = new Feature({
          geometry: this.createGeomInFeature(element.geometry),
          levelid: 4,
          data: element,
          id: element.id,
          layerName: config.name, //图层名称
          name: element.name ? element.name : "点的数据名称",
        });
        if (element.styles) {
          const style = new olStyle(element.styles).style;
          console.log(style);

          currentFeature.setStyle(style);
        } else {
          const style = new olStyle(config.styles).style;
          currentFeature.setStyle(style);
        }
        features.push(currentFeature);
      });
    }
    pointLayer.layer.getSource().addFeatures(features);
  }
  // 根据geom数据创建要素的几何图形，（点，线，面）
  createGeomInFeature(geometry) {
    let pointCoordinates = null;
    let GeometryData;
    let points = [];
    switch (geometry.type) {
      case "point":
        points = this.MapUtils.getWkt([geometry.geom]);
        pointCoordinates = this.convertPointsDataToArray(points);
        GeometryData = new Point(pointCoordinates);
        break;
      case "LineString":
        let feature1 = this.MapUtils.getArrayMultiPolygon(geometry.geom);
        GeometryData = feature1.getGeometry();
        break;
      case "line":
        pointCoordinates = geometry.coordinates;
        GeometryData = new LineString(pointCoordinates);
        break;
      case "MultiPolygon": //多面
        let feature = this.MapUtils.getArrayMultiPolygon(geometry.geom);
        GeometryData = feature.getGeometry();
        break;
      case "polygon": //显示多面的第一个面
        points = this.MapUtils.getMULTIPOLYGON([geometry.geom])[0];
        pointCoordinates = this.convertPointsDataToArray(points);
        GeometryData = new Polygon([pointCoordinates]);
        break;
    }
    return GeometryData;
  }
  // 数据处理，将数据转换为Geom数组构建形式
  convertPointsDataToArray(points) {
    let pointsArray;
    // let points = geometry.points;
    if (points.length <= 1) {
      pointsArray = [points[0].x, points[0].y];
    } else {
      pointsArray = [];
      points.forEach((value) => {
        let point = [value.x, value.y];
        pointsArray.push(point);
      });
    }
    return pointsArray;
  }

  /**
   * 添加自己定义的layer
   */
  addLayerToMap(customLayer) {
    if (customLayer["layer"] && customLayer["id"]) {
      this.currentMap.addLayer(customLayer.layer);
    }
  }
  /**
   * 图层id
   * @param {*} layerId
   */
  removeVectorLayer(layerId) {
    this.removeLayerById(layerId, this.industryMapLayers);
  }

  /**
   *
   * @param {*} id 图层id
   * @param {*} layers 图层列表
   */
  removeLayerById(id, layers) {
    layers.forEach((value, index) => {
      if (value.id === id) {
        this.currentMap.removeLayer(value.layer);
        this.industryMapLayers.splice(index, 1);
      }
    });
  }

  /**
   * 通过服务创建wfs图层
   * @param {*} layerId 图层id
   * @param {*} url 图层url
   * @param {*} style 图层样式
   */
  createwfsLayer(layerId, url, style) {
    let pointLayer = {
      id: layerId,
      layer: null,
    };
    let styles = style;
    let Source = this.createwfsVectorSource(url);
    let vectorLayer = new VectorLayer({
      source: Source,
      style: (feature) => {
        styles.text.text = feature.get("name");
        return new olStyle(styles).style;
      },
      zIndex: style.zIndex,
    });
    pointLayer.layer = vectorLayer;
    this.industryMapLayers.push(pointLayer);
    this.addLayerToMap(pointLayer);
  }

  /**
   * 创建wfs图层
   * @param {*} url
   * @returns
   */
  createwfsVectorSource(url) {
    return new VectorSource({
      url: url,
      format: new GeoJSON(),
    });
  }

  /**
   * 通过服务请求wms图层
   * @param {*} layerId
   * @param {*} wmsparams
   * @param {*} url
   */
  createwmsLayer(layerId, wmsparams) {
    let pointLayer = {
      id: layerId,
      layer: null,
    };
    let Source = this.createwmsVectorSource(wmsparams);
    let vectorLayer = new TileLayer({
      source: Source,
      zIndex: wmsparams.zIndex,
    });
    pointLayer.layer = vectorLayer;
    this.industryMapLayers.push(pointLayer);
    this.addLayerToMap(pointLayer);
  }

  /**
   * 创建wfs图层
   * @param {*} url
   * @returns
   */
  createwmsVectorSource(param) {
    return new TileWMS({
      url: param.url,
      params: {
        LAYERS: param.LAYERS,
        TILED: true,
        VERSION: "1.1.1",
      },
      tileGrid: new TileGrid({
        tileSize: [256, 256],
        origin: [-400.0, 400.0],
        // resolutions: [0.00951784402332112, 0.00475892201166056, 0.00237946100583028, 0.00118973050291514, 5.9486525145757E-4, 2.97432625728785E-4, 1.5228550437313792E-4, 7.614275218656896E-5, 3.807137609328448E-5]
        resolutions: param.resolutions,
      }),
      hidpi: false,
      projection: "EPSG:4326",
      serverType: "geoserver",
      transition: 0,
    });
  }
  /**
   * 获取绘制专用图层
   */
  getDrawLayer() {
    return this.interactionDrawLayer;
  }

  /**
   * 创建绘制专用图层
   * @param style 样式
   */
  createDrawLayer(style) {
    const drawVectorLayer = this.createVectorLayer(style);
    // if (style) {
    //   drawVectorLayer.setStyle(style);
    // }
    this.interactionDrawLayer = {
      id: "drawlayer",
      layer: drawVectorLayer,
      type: "draw",
      zindex: 11,
      visible: true,
    };
    this.currentMap.addLayer(this.interactionDrawLayer.layer);
  }

  /**
   * 创建普通矢量图层
   * @param style 矢量图层样式
   */
  createVectorLayer(style) {
    let defaultStyle = this.initVectorStyle();
    let currentStyle = null;
    if (style) {
      currentStyle = new Style(style).style;
    }
    const layer = new VectorLayer({
      source: this.createVectorSource(),
      style: style ? currentStyle : defaultStyle,
      zIndex:100
    });
    return layer;
  }

  // 创建普通矢量图层数据源
  createVectorSource() {
    const source = new VectorSource({ wrapX: false });
    return source;
  }

  // 初始化默认矢量图层样式
  initVectorStyle() {
    let defaultStyle = LayerConstant.DEFAULT_DRAW_STYLE[1];
    const marker = require("../assets/mapimg/marker.png");
    defaultStyle.setImage(
      new Icon({
        src: marker,
        size: [32, 62],
      })
    );
    return defaultStyle;
  }

  /**
   * 创建测量专用图层
   * @param style 样式
   */
  createMeasureLayer(style) {
    const measureLayer = this.createVectorLayer();
    if (style) {
      measureLayer.setStyle(style);
    }
    let measureId = "measure" + this.measureLayerId;
    let measureLayerObj = {
      id: measureId,
      layer: measureLayer,
      type: LayerConstant.MEASURE_LAYER_TYPE,
      zIndex: 100,
      visible: true,
    };

    this.interactionMeasureLayers.push(measureLayerObj);
    this.measureLayerId = this.measureLayerId + 1;
    this.currentMap.addLayer(measureLayerObj.layer);
    return measureLayerObj;
  }

  /**
   * 获取测量图层列表
   */
  getMeasureLayers() {
    return this.interactionMeasureLayers;
  }
}
